from django.db import models
from django.conf import settings
import uuid
from django.utils import timezone

class Order(models.Model):
    STATUS_CHOICES = (
        ('paid', '已付款'),
        ('shipped', '已发货'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    )

    order_number = models.CharField(max_length=50, unique=True, verbose_name='订单编号')
    customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='orders', verbose_name='客户')
    salesman = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sales_orders', null=True, blank=True, verbose_name='销售员')
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='总金额')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='paid', verbose_name='状态') # 修改默认状态为 'paid'
    payment_method = models.CharField(max_length=50, null=True, blank=True, verbose_name='支付方式')
    payment_time = models.DateTimeField(null=True, blank=True, verbose_name='支付时间')
    address = models.TextField(verbose_name='地址', default='未提供地址')
    phone = models.CharField(max_length=20, verbose_name='电话')
    remark = models.TextField(null=True, blank=True, verbose_name='备注')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '销售订单'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['status']),
            models.Index(fields=['customer']),
        ]

    def __str__(self):
        return f'订单 #{self.order_number}'
    
    def save(self, *args, **kwargs):
        # 如果是新创建的订单，生成订单编号
        if not self.order_number:
            self.order_number = f"SO{timezone.now().strftime('%Y%m%d')}{str(uuid.uuid4().int)[:6]}"
        super().save(*args, **kwargs)

class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items', verbose_name='订单')
    product = models.ForeignKey('products.Product', on_delete=models.CASCADE, related_name='order_items', verbose_name='商品')
    quantity = models.PositiveIntegerField(default=1, verbose_name='数量')
    unit_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='单价')
    total_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='总价')
    # 在 OrderItem 模型中
    warehouse = models.ForeignKey('warehouse.Warehouse', on_delete=models.SET_NULL, null=True, blank=True, related_name='order_items', verbose_name='仓库')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '订单项'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.product.name} x {self.quantity}'
    
    def save(self, *args, **kwargs):
        # 自动计算总价
        self.total_price = self.quantity * self.unit_price
        super().save(*args, **kwargs)